<?php
namespace org\phpstruct\db\ORM;

use org\phpstruct\core;
use org\phpstruct\db;
use org\phpstruct\db\I;
use org\phpstruct\db\PDO;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of WhereCondition
 *
 * @author unieuro
 */
class WhereCondition {

  //put your code here
  private $name;
  private $value;
  private $comp = 'eq';
  const EQUALS = '=';
  const NOT_EQUALS = '!=';
  const GREATER_THAN = '>=';
  const LESS_THAN = '<=';
  const LIKE = 'LIKE';
  const IN = 'IN';
  const NOT_IN = 'NOT IN';

  function __construct($name, $value, $comp = WhereCondition::EQUALS) {

    $escname = $dot = '';
    if (preg_match("/\./", $name)) {
      $parts = explode('.', $name);

      foreach ($parts as $p) {
        $escname.= "{$dot}`{$p}`";
        $dot = '.';
      }
    } else {
      $escname = "`{$name}`";
    }
    $this->name = $escname;
    $this->value = $value;
    $this->comp = $comp;
  }

  public static function quote(&$s) {
    return sprintf("'%s'", addslashes($s));
  }

  public function __toString() {
    if (is_array($this->value)) {

      $value = sprintf(" %s (%s)", self::IN, implode(',', array_map('WhereCondition::quote', $this->value)));
    } else if (is_string($this->value)) {
      if ($this->comp == self::LIKE) {
        $value = " {$this->comp} '" . addslashes($this->value) . "'";
      } else {
        if (preg_match("/^:/", $this->value)) {
          $value = " {$this->comp} {$this->value}";
        } else {
          if (preg_match("/NOW\(\)/", $this->value)) {
            $value = " {$this->comp} {$this->value} ";
          } else {
            $value = " {$this->comp} '" . addslashes($this->value) . "'";
          }
        }
      }
    } else if (is_numeric($this->value)) {
      $value = " {$this->comp} {$this->value}";
    } else if (is_bool($this->value)) {
      $value = $this->value ? " {$this->comp} TRUE" : " {$this->comp} FALSE";
    } else if (is_null($this->value)) {
      switch ($this->comp) {
        case self::EQUALS:
          $value = 'IS NULL';
          break;
        case self::LIKE:
          $value = 'LIKE';
          break;
        case self::NOT_EQUALS:
        case self::GREATER_THAN:
        case self::LESS_THAN:
          $value = 'IS NOT NULL';
          break;
      }
    } else {
      $value = "'" . addslashes($this->value) . "'";
    }
    $str = "{$this->name} {$value}";

    return $str;
  }

  public function getName() {
    return $this->name;
  }

  public function setName($name) {
    $this->name = $name;
  }

  public function getValue() {
    return $this->value;
  }

  public function setValue($value) {
    $this->value = $value;
  }

}
